package pri.controller.login;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pri.pojo.Admin;
import pri.service.login.LoginService;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

//    @RequestMapping("/dis")
//    public String disPage(){
//
//        return "back/login/discuss";
//    }
//    @Autowired
//    private CartService cartService;

    //主页面

    @RequestMapping("/home")
    public String mainPage(){

        return "back/login/login";
    }

    //跳转到登录界面
    @RequestMapping("/login")
    public String login(){
        //获取到ServletRequestAttributes 里面有 RequestContextHolder
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取到Request对象
        HttpServletRequest request = attrs.getRequest();
        //获取到Session对象
        HttpSession session = request.getSession();
        //获取到Response对象
        HttpServletResponse response = attrs.getResponse();
        if (session.getAttribute("admin")!=null){
            return "redirect:/product/home";
        }

        Cookie[] cookies = null;
        // 获取cookies的数据,是一个数组
        cookies = request.getCookies();
        String adminName = "";
        String password = "";
        if(cookies !=null){
            for(int i = 0;i < cookies.length;i++){  //遍历cookie对象集合
                if(cookies[i].getName().equals("adminName")){
                    adminName = URLDecoder.decode(cookies[i].getValue().split("#")[0]);//获取用户名
                    System.out.println("yonghuming:"+adminName);
                }

                if(cookies[i].getName().equals("password")){
                    password = URLDecoder.decode(cookies[i].getValue().split("#")[0]);//获取密码
                    System.out.println("mima:"+password);
                }
            }
        }

        if (!adminName.isEmpty() && !password.isEmpty()){
            System.out.println("zheli");
            Admin admin = new Admin();
           admin.setAdminName(adminName);
           admin.setPassword(password);
           Admin loginAdmin = loginService.selectByAdminNameAndPassword(admin);
            if (loginAdmin!=null){
                session.setAttribute("admin",loginAdmin);
                return "redirect:/doStatistics";
            }else{
                return "redirect:/login/logout";
            }
        }
        return "back/login/login";
    }

    //    用户登录
    @RequestMapping("/doLogin")
    @ResponseBody
    public Map<String,Object> doLogin(String data,HttpServletRequest request,HttpServletResponse response,HttpSession session){

        Map<String,Object> jsonMap = new HashMap<>();
        //先获取字符串json
        //转换为json对象
        JSONObject jsonObject = JSONUtil.parseObj(data);
        System.out.println("str:"+data);
        Admin admin = new Admin();
        admin.setAdminName((String) jsonObject.get("adminName"));
        admin.setPassword((String)jsonObject.get("password"));
        System.out.println(admin);
        Admin loginAdmin = loginService.selectByAdminNameAndPassword(admin);
        System.out.println(loginAdmin);
        if (loginAdmin!=null){
            session.setAttribute("admin",loginAdmin);
            System.out.println(loginAdmin);

            //成功后判断加不加cookie
            if ((boolean)jsonObject.get("rememberMe")){
                System.out.println("hello");
                Cookie cookieu = new Cookie("adminName",loginAdmin.getAdminName());
                cookieu.setMaxAge(60*2);
                Cookie cookiep = new Cookie("password",loginAdmin.getPassword());
                cookiep.setMaxAge(60*2);
                response.addCookie(cookieu);
                response.addCookie(cookiep);

            }
            jsonMap.put("code","1");

        }else{
            jsonMap.put("code","0");
        }
        System.out.println(jsonMap.get("code"));
        return jsonMap;

    }

    //跳转到登录成功的界面
    @RequestMapping("loginSuccess")
    public String suc(){
        return "redirect:/doStatistics";
    }



    @RequestMapping("/logout")
    public String logout(){
        //获取到ServletRequestAttributes 里面有 RequestContextHolder
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取到Request对象
        HttpServletRequest request = attrs.getRequest();
        //获取到Session对象
        HttpSession session = request.getSession();
        //获取到Response对象
        HttpServletResponse response = attrs.getResponse();

        //清空所有session
        Enumeration em = session.getAttributeNames();
        while(em.hasMoreElements()){
            session.removeAttribute(em.nextElement().toString());
        }

        //清除cookie
        Cookie[] cookies = null;
        cookies = request.getCookies();
        for(int i=0;i<cookies.length;i++){
            cookies[i].setMaxAge(0);
            response.addCookie(cookies[i]);
        }

        return "redirect:/login/login";
    }


    //修改密码
//    @RequestMapping("/doChange")
//    public String doChange(User user){
//        if(loginService.updateUser(user)>0){
//            return "/front/login/login";
//        }
//        return "/front/login/register";
//
//    }



    //注册用户

//    @RequestMapping("/doRegister")
//    @ResponseBody
////    User user,String code,HttpSession session
//    public String doRegister(){
//        //获取到ServletRequestAttributes 里面有 RequestContextHolder
//        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        //获取到Request对象
//        HttpServletRequest request = attrs.getRequest();
//        //获取到Session对象
//        HttpSession session = request.getSession();
//        //获取到Response对象
//        HttpServletResponse response = attrs.getResponse();
//        //先获取字符串json
//        String jsonStr = request.getParameter("content");
//        //转换为json对象
//        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
//        //创建Json对象
//        JSONObject jsonMap = new JSONObject();
//
//        String code = (String) jsonObject.get("code");
//        if (session.getAttribute("code").equals(code)){
//            User user = new User();
//            user.setUserName((String) jsonObject.get("username"));
//            user.setNickName((String) jsonObject.get("nickname"));
//            user.setPassword((String) jsonObject.get("password"));
//            user.setEmail((String) jsonObject.get("email"));
//            String id = Common.getUUID(12);
//            user.setUserId(id);
//            if(loginService.insertUser(user)){
//                session.setAttribute("user",user);
//                jsonMap.put("code","1");
//                jsonMap.put("msg","注册成功");
//            }else {
//                jsonMap.put("code","0");
//                jsonMap.put("msg","验证码不正确");
//            }
//        }
//        return jsonMap.toString();
//    }


}
